package com.bw.launcher.splash

import androidx.lifecycle.viewModelScope
import com.bw.common.mvi.BaseViewModel
import com.bw.common.utils.LockingUtils
import com.bw.launcher.splash.entity.LockErroEntity
import com.bw.launcher.splash.entity.WhiteListEntity
import com.bw.launcher.splash.entity.WhiteResponseEntity
import com.bw.launcher.splash.entity.WhiteState
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flatMapConcat
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch

class SplashViewModel : BaseViewModel<SplashRepo,WhiteState>(){

    override fun createRepo(): SplashRepo {
        return SplashRepo()
    }

    override fun createState(): WhiteState {
        return WhiteState(false,false,ArrayList())
    }

    fun requestWhite(){
        viewModelScope.launch {
            subFlow(repo.requestLock()).flatMapConcat {
                if (it.statusCode == 200){
                    val erroEntity = LockErroEntity()
                    erroEntity.statusCode = 100
                    erroEntity.msg = "锁屏"
                    return@flatMapConcat subFlow(flow { emit(erroEntity) })
                }else{
                    return@flatMapConcat subFlow(repo.requestWhite())
                }
            }.collect{
                if (it.statusCode == 100){
                    LockingUtils.clearDisk()
                    mutableContainer.updateUiState { copy(true,false,ArrayList()) }
                }else{
                    var entity : WhiteResponseEntity = it as WhiteResponseEntity
                    mutableContainer.updateUiState { copy(false,true,entity.datas) }
                }
            }
        }
    }

}